package com.myfum.wingplayer.commands
{
	import com.myfum.wingplayer.entity.ProgramData;
	import com.myfum.wingplayer.entity.ScheduleItemData;
	import com.myfum.wingplayer.model.ProgramLocator;
	import com.myfum.wingplayer.utils.DefaultProgram;
	import com.myfum.wingplayer.utils.TaskManager;
	
	import flash.filesystem.File;
	
	import org.robotlegs.mvcs.Command;
	
	public class ScheduleChangedCommand extends Command
	{
		[Inject]
		public var locator:ProgramLocator;
		[Inject]
		public var task:TaskManager;
		
		public function ScheduleChangedCommand()
		{
			super();
		}
		
		override public function execute():void{
			var d:Date = new Date();
			var path:String = getProgramPath(d);
			var file:File;
			var pd:ProgramData;
			
			if(path == null || path == ""){
				//use default program
				locator.currentProgram = DefaultProgram.getDefaultProgram();
			}else{
				file = new File(path);
				if(file.exists){
					pd = new ProgramData(file);
					pd.serialize();
					locator.currentProgram = pd;
				}else{
					//use default program
					locator.currentProgram = DefaultProgram.getDefaultProgram();
				}
			}
		}
		
		private function getProgramPath(date:Date):String{
			var p:String;
			for(var i:int = 0;i<locator.arrayCollection.length;i++){
				var d:ScheduleItemData = locator.arrayCollection.getItemAt(i) as ScheduleItemData;
				if(d == null){
					return null;
				}
				var sd:Date = new Date(date.fullYear, date.month, date.date, d.startTime.hours, d.startTime.minutes, d.startTime.seconds);
				var ed:Date = new Date(date.fullYear, date.month, date.date, d.endTime.hours, d.endTime.minutes, d.endTime.seconds);
				if(date.time >= sd.time && date.time < ed.time){
					p = d.programPath;
					break;
				}
			}
			return p;
		}
		
	}
}